# Copyright (c) 2025, yuxinyong and contributors
# For license information, please see license.txt

import frappe
from frappe import _
from frappe.model.document import Document
from frappe.model.naming import make_autoname
from frappe.utils import nowdate


class ShoeSample(Document):
    def onload(self):
        self.auto_fill_related_samples()

    def before_print(self, settings=None):
        self.auto_fill_related_samples()

    def auto_fill_related_samples(self):
        related_samples = frappe.get_all(self.doctype, 
            filters={            
                'style': self.style,
                'customer': self.customer,
                'season': self.season,
                'docstatus': 1,
                #'name': ['!=', self.name]
            },
            fields=["name as sample", "sample_type", "shoe_material", "shoe_color", "status"]
        )
        for row in related_samples:
            #row.sample = f"/app/shoe-sample/{row.sample}"
            self.append("related_samples",  row)

    def validate(self):
        self.loading_processes()
        self.related_samples = []
        # 试版只做一支鞋，数量就是0.5双
        if self.sample_stage == "Proto":
            self.qty = 0.5

    def before_update_after_submit(self):
        self.related_samples = []

    @frappe.whitelist()
    def create_items(self):
        new_item_doc = frappe.new_doc("Item")
        new_item_doc.update({
            'item_code': make_autoname('10.####'),
            #'item_group': '',        #取库存设置的默认值
            'default_uom': 'Pair',
            'item_name': f"{self.style} {self.shoe_material} {self.shoe_color}",
            'shoe_customer': self.customer,
            'last': self.last,
            'style': self.style,
            'style_name': self.style_name,
            'shoe_color': self.shoe_color,
            'shoe_material': self.shoe_material
        })
        new_item_doc.insert(ignore_permissions=1)
        frappe.db.set_value(self.doctype, self.name, 'item_code', new_item_doc.name)

        return True

    def on_submit(self):
        self.create_sampling_job_card()

    def on_cancel(self):
        self.delete_sampling_job_card()

    def loading_processes(self):
        if self.sampling_process_template and not self.processes:
            template_doc = frappe.get_doc("Shoe Sampling Process Template", self.sampling_process_template)
            for row in template_doc.processes:
                self.append("processes", {
                    "sampling_process": row.sampling_process,
                    "sampling_process_ch": row.sampling_process_ch,
                    "description": row.description
                })

    def create_sampling_job_card(self):
        for row in self.processes:
            create_sampling_job_card(self, row)
    
    def delete_sampling_job_card(self):
        for d in frappe.get_all("Sampling Job Card", ["name"], {"sample": self.name}):
            frappe.delete_doc("Sampling Job Card", d.name)

    def update_status(self, status=None):
        """Update status if unknown"""
        if status != "Stopped" and status != "Closed":
            status = self.get_status(status)

        if status != self.status:
            self.db_set("status", status)

        return status

    def get_status(self, status=None):
        if not status:
            status = self.status

        if self.docstatus == 0:
            status = "Draft"
        elif self.docstatus == 1:
            if status != "Stopped":
                status = "Not Started"
        else:
            status = "Cancelled"

        return status

def create_sampling_job_card(sample, row, auto_create=False):
    doc = frappe.new_doc("Sampling Job Card")
    doc.update(
        {
            "sample": sample.name,            
            "sampling_process": row.get("sampling_process"),
            "workstation": row.get("workstation"),
            "posting_date": nowdate(),
            "qty": row.qty or sample.get("qty", 0),
            "sample_process_row_id": row.get("name"),
            "company": sample.company,
            #"sequence_id": row.get("sequence_id"),
        }
    )

    doc.insert()

    return doc

@frappe.whitelist()
def stop_unstop(sample, status):
    """Called from client side on Stop/Unstop event"""

    if not frappe.has_permission("Shoe Sample", "write"):
        frappe.throw(_("Not permitted"), frappe.PermissionError)

    sample_doc = frappe.get_doc("Shoe Sample", sample)

    if sample_doc.status == "Closed":
        frappe.throw(_("Closed Shoe Sample can not be stopped or Re-opened"))

    sample_doc.update_status(status)
    frappe.msgprint(_("Shoe Sample has been {0}").format(status))

    return sample_doc.status

@frappe.whitelist()
def close_sample(sample, status):
    if not frappe.has_permission("Shoe Sample", "write"):
        frappe.throw(_("Not permitted"), frappe.PermissionError)

    sample = frappe.get_doc("Shoe Sample", sample)

    #暂时不考虑任务单状态
    # if sample.get("processes"):
    #     job_cards = frappe.get_list(
    #         "Sampling Job Card",
    #         filters={"sample": sample.name, "status": "Work In Progress", "docstatus": 1},
    #         pluck="name",
    #     )

    #     if job_cards:
    #         job_cards = ", ".join(job_cards)
    #         frappe.throw(
    #             _("Can not close Shoe Sample. Since {0} Sampling Job Cards are in Work In Progress state.").format(
    #                 job_cards
    #             )
    #         )

    sample.update_status(status)
    frappe.msgprint(_("Shoe Sample has been {0}").format(status))
    return sample.status
